<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="large" :inline="true">
      <el-form-item label="商品" prop="goodsId">
        <el-select
          v-model="queryParams.goodsId"
          placeholder="请选择商品"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        >
          <el-option
            v-for="item in goodsList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="sku编码" prop="stockSku">
        <el-input
          v-model="queryParams.stockSku"
          placeholder="请输入sku编码"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="large"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="large" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="18">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="large"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="large"
          :disabled="single"
          @click="handleUpdate"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="large"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="large"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
    </el-row>
    <el-table
      class="user-table"
      v-loading="loading"
      :data="skuList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="sku编号" prop="id" width="100" align="center" />
      <el-table-column
        label="商品名称"
        prop="goods.goodsName"
        :show-overflow-tooltip="true"
        width="150"
        align="center"
      />
      <el-table-column
        label="sku编码"
        prop="stockSku"
        width="150"
        align="center"
      >
      </el-table-column>
      <el-table-column
        label="当前价格"
        prop="price"
        width="100"
        align="center"
      />
      <el-table-column
        label="原价"
        prop="oldPrice"
        width="100"
        align="center"
      />
      <el-table-column
        label="库存数量"
        prop="inventory"
        width="100"
        align="center"
      >
      </el-table-column>

      <el-table-column
        label="商品图片"
        prop="picture"
        width="150"
        align="center"
      >
        <template slot-scope="{ row }">
          <el-avatar
            shape="square"
            :src="row.picture"
            size="medium"
          ></el-avatar>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status" width="150" align="center">
        <template slot-scope="{ row }">
          <el-tag :type="row.status === 0 ? 'primary' : 'danger'">{{
            row.status == 0 ? "正常" : "禁用"
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            size="large"
            type="text"
            icon="el-icon-edit"
            @click="relative(scope.row)"
            >关联属性</el-button
          >
          <el-button
            size="large"
            type="text"
            icon="el-icon-edit"
            @click="relative(scope.row)"
            >修改</el-button
          >
          <el-button
            size="large"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-row :span="24" style="margin-top: 20px">
      <el-col :span="24" :offset="15">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageNo"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="queryParams.pageSize"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
        >
        </el-pagination>
      </el-col>
    </el-row>
    <!-- 添加或修改会员信息对话框 -->
    <el-dialog
      :title="(form.id === null ? '添加' : '修改') + 'sku信息'"
      :visible.sync="open"
      width="500px"
      height="600px"
      lock-scroll
      top="5vh"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="100px"
        size="mini"
      >
        <el-form-item label="商品" prop="goodsId">
          <el-select
            v-model="form.goodsId"
            placeholder="请选择商品"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="(item, index) in goodsList"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="库存sku" prop="stockSku">
          <el-input v-model="form.stockSku" placeholder="请输入库存sku" />
        </el-form-item>
        <el-form-item label="当前价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入当前价格" />
        </el-form-item>
        <el-form-item label="原价" prop="oldPrice">
          <el-input v-model="form.oldPrice" placeholder="请输入原价" />
        </el-form-item>
        <el-form-item label="库存数量" prop="inventory">
          <el-input v-model="form.inventory" placeholder="请输入库存数量" />
        </el-form-item>
        <el-form-item label="商品图片" prop="picture">
          <el-upload
            class="avatar-uploader"
            action="/api/file/upload"
            name="file"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="form.picture"
              :src="form.picture"
              class="avatar"
              alt="商品图片"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">
              请上传 大小不超过 <span style="color: red">5MB </span>格式为
              <span style="color: red">png/jpg/jpeg</span> 的图片
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="0">正常</el-radio>
            <el-radio :label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "UserList",
  data() {
    return {
      totalCount: 0,
      //搜索参数
      queryParams: {
        goodsId: null,
        stockSku: null,
        pageNo: 1,
        pageSize: 5,
      },
      skuList: [],
      form: {
        id: null, // skuid
        goodsId: null, // 商品Id
        stockSku: "", //商品sku；
        price: null, //当前价格
        oldPrice: "", //原价
        inventory: null, //库存数量
        picture: "", //商品图片
        status: null, //状态（0.正常 1.禁用）
      },
      goodsList: [],
      rules: {
        goodsId: [{ required: true, message: "请选择商品", trigger: "change" }],
        stockSku: [
          { required: true, message: "请输入sku编码", trigger: "blur" },
        ],
        price: [{ required: true, message: "请输入当前价格", trigger: "blur" }],
        oldPrice: [{ required: true, message: "请选择原价", trigger: "blur" }],
        inventory: [
          { required: true, message: "请输入库存数量", trigger: "blur" },
        ],
        status: [{ required: true, message: "请选择状态", trigger: "change" }],
      },
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      open: false, //是否打开添加或修改会员信息对话框
      loading: false,
      showSearch: true,
      ids: [], //选中的用户id集合
    };
  },
  created() {
    this.getList();
    this.getGoodsList();
  },
  methods: {
    //获取sku列表
    async getList() {
      this.loading = true;
      try {
        const res = await this.$axios("/api/sku/list", {
          params: this.queryParams,
        });
        if (res.data.code === 200) {
          this.totalCount = res.data.data.totalCount;
          this.skuList = res.data.data.data;
        }
      } catch (error) {
        this.$message.error("获取sku列表失败");
      } finally {
        this.loading = false;
      }
    },
    async getGoodsList() {
      const res = await this.$axios("/api/goods/all");
      if (res.data.code === 200) {
        this.goodsList = res.data.data.map((item) => {
          return {
            value: item.id,
            label: item.goodsName,
          };
        });
      }
    },
    //查询
    handleQuery() {
      this.$refs.queryForm.validate((valid) => {
        if (valid) {
          this.getList();
        } else {
          return false;
        }
      });
    },
    //重置查询条件
    resetQuery() {
      (this.queryParams.goodsId = null),
        (this.queryParams.stockSku = null),
        (this.queryParams.userLevel = "");
      this.getList();
    },
    //当页面变化时的事件
    handleCurrentChange(pageNo) {
      //修改当前页码
      this.queryParams.pageNo = pageNo;
      //执行查询
      this.handleQuery();
    },

    //每当页数量下拉框选项切换变化时的事件
    handleSizeChange(pageSize) {
      //修改查询条件中的的每页数量
      this.queryParams.pageSize = pageSize;
      //执行查询
      this.handleQuery();
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          if (this.form.id !== null) {
            //修改
            const res = await this.$axios.post("/api/sku/update", this.form);
            if (res.data.code === 200) {
              this.$message.success("修改成功");
              this.open = false;
              this.getList();
            } else {
              this.$message.error(res.data.msg);
            }
          } else {
            //添加
            const res = await this.$axios.post("/api/sku/add", this.form);
            if (res.data.code === 200) {
              this.$message.success("添加成功");
              this.open = false;
              this.getList();
            } else {
              this.$message.error(res.data.msg);
            }
          }
          this.form.avatar = "";
          this.$refs["form"].resetFields();
        }
      });
    },
    //取消按钮
    cancel() {
      this.open = false;
      this.$refs["form"].resetFields();
    },
    handleAdd() {
      (this.form = {
        id: null, // skuid
        goodsId: null, // 商品Id
        stockSku: "", //商品sku；
        price: null, //当前价格
        oldPrice: "", //原价
        inventory: null, //库存数量
        picture: "", //商品图片
        status: null, //状态（0.正常 1.禁用）
      }),
        (this.open = true);
    },
    async handleUpdate(row) {
      const id = row.id || this.ids[0];
      const res = await this.$axios(`/api/sku/detail?id=${id}`);
      if (res.data.code === 200) {
        this.form = res.data.data;
        this.open = true;
      } else {
        this.$message.error(res.data.msg);
      }
    },
    handleDelete(row) {
      const id = [row.id] || this.ids;
      this.$confirm(`是否删除sku编号为${id}的sku信息`, "提示", {
        type: "warning",
      })
        .then(async () => {
          const res = await this.$axios.post("/api/sku/del", id);
          if (res.data.code === 200) {
            this.$message.success("删除成功");
            this.getList();
          } else {
            this.$message.error(res.data.msg);
          }
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    handleExport() {
      // 导出逻辑
      this.$message.info("暂不支持导出功能");
    },
    // 头像上传成功的回调
    handleAvatarSuccess(res) {
      if (res.code !== 200) {
        this.$message.error("图片上传失败");
        return;
      }
      this.$message.success("图片上传成功");
      // 将返回的头像地址赋值给form.avatar
      this.form.picture = res.data;
    },
    beforeAvatarUpload(file) {
      const isLt5M = file.size / 1024 / 1024 < 5;
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isPNG = file.type === "image/png" || file.type === "image/jpeg";
      if (!isJPG && !isPNG) {
        this.$message.error("上传头像图片只能是 JPG/PNG 格式!");
      }
      if (!isLt5M) {
        this.$message.error("上传头像图片大小不能超过 5MB!");
      }
      return isJPG && isLt5M && isPNG;
    },
    //多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    relative(row) {
      this.$router.push(
        `/skuRelative?stockSku=${row.stockSku}&goodsId=${row.goodsId}`
      );
    },
  },
};
</script>

<style scoped>
.user-table {
  margin-top: 20px;
}
.app-container {
  padding: 20px;
}
.el-form-item {
  margin-bottom: 20px;
}
.el-form-item label {
  font-size: 16px;
  font-weight: bold;
}
.avatar-uploader .el-upload {
  border: 1px dotted red !important;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
